<template>
  <div class="login-container">
    <!-- 导航栏 -->
    <van-nav-bar fixed title="黑马头条-登录" />
    <!-- 登录信息 -->
    <van-form @submit="login">
      <!-- 手机号 -->
      <van-field
        type="tel"
        v-model="form.mobile"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="rules.mobile"
      ></van-field>
      <!-- 密码 -->
      <van-field
        type="password"
        v-model="form.code"
        placeholder="请输入密码"
        label="密码"
        required
        :rules="rules.code"
      >
      </van-field>
      <!-- 按钮 -->
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { LoginAPI } from '../API/userAPI'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data () {
    return {
      form: {
        mobile: '13333333333', // 手机号
        code: 246810 // 密码
      },
      rules: { // 表单校验规则对象
        // required必填验证  必填 错误信息 触发情况  pattern 正则输入验证
        mobile: [{ required: true, message: '请输入手机号', trigger: 'onBlur' }, { pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'onBlur' }],

        code: [{ required: true, message: '请输入密码', trigger: 'onBlur' }]
      }
    }
  },
  methods: {
    ...mapMutations(['updateTokenInfo']), // 映射store中的updateTokenInfo方法

    async login () {
      const { data: res } = await LoginAPI(this.form)
      console.log(res)
      // 判断是否登录成功
      // 如果成功把token存储在vuex中的state中
      if (res.message === 'OK') {
        this.updateTokenInfo(res.data)
        // 跳转到主页
        this.$router.push('/')
      }
    }
  }

}
</script>

<style lang="less" scoped>
.login-container {
  padding-top: 46px;
}
</style>
